require "Net/send_Msg"
require 'View/UIBase/UIBase'

UIGuildBoss = UIBase.New(PanelNames.UIGuildBoss);
function UIGuildBoss.Init(data)
    UIBase.Init(UIGuildBoss);
end

--定义控件
function UIGuildBoss:OnCreate()
    --参数
    self.battleCount = 0;--剩余能挑战次数
    self.curTime = 0;
    --utimer
    self.refreshTimer = nil;--boss刷新倒计时计时器
    ---@type Fairy.GComponent
    --排行榜组件
    self.rankCom = self:GetChild("rankCom");
    --我的排名
    self.myRank = self.rankCom:GetChild("my");
    --红点
    self.redDot = self:GetChild("Btn_gotowar"):GetChild("UIRedDots")

    --table
    ---@param guildBossInfo GuildBossInfo
    self.guildBossInfo = {};

    --list
    --工会boss奖励列表
    self.rewardList = self:GetChild("dynamicList_rewardpreview");
    --贡献榜排行列表
    self.rankList = self.rankCom:GetChild("ranklist");

    --controller
    --共享榜 0不显示 1显示
    self.contributionListCtrl = self:GetController("Contributionlist");
    --技能详情 0不显示 1显示
    self.skillShowCtrl = self:GetController("skillDec");
    --小提示 0不显示 1显示
    self.tipsPageCtrl = self:GetController("tips");
    --无人上榜状态 0无人 1有人
    self.noBodyRankCtrl = self.rankCom:GetController("state")
    --红点 0隐藏 2显示
    self.redDotCtrl = self.redDot:GetController("c1");
    --text
    self.bossNameText = self:GetChild("Text_title");--boss名字
    self.timesTodayText = self:GetChild("Text_timestoday");--当前挑战次数
    self.resetTime = self:GetChild("Text_resettime");--重置时间
    self.skillName = self:GetChild("BossSkillName");--选择后展示技能名
    self.skillDec = self:GetChild("BossSkillTips");--选择后展示技能详情
    self.TipsText = self:GetChild("Text_hint");--提示
    self.TipsText.text = getLanguage("GuildInvestment_1123")
    --btn
    self.backBtn = self:GetChild("Btn_return");--返回按钮
    self.battleBtn = self:GetChild("Btn_gotowar");--开战按钮
    self.rankBtn = self:GetChild("Btn_contributionlist");--排行榜按钮
    self.rankBtn.title = getLanguage("GuildInvestment_1124");
    self.rankBackBtn = self.rankCom:GetChild("btnClose");--排行榜返回按钮
    self.rankBackBGBtn = self.rankCom:GetChild("bgClose");--排行榜返回按钮

    self.tipsBtn = self:GetChild("Btn_tips");--提示按钮
    self.skillIcon1Btn = self:GetChild("Btn_TrickGroup");--1技能
    self.skillIcon2Btn = self:GetChild("Btn_SpecailGroup");--2技能
    self.skillIcon3Btn = self:GetChild("Btn_SpecailTwoGroup");--3技能
    self.skillIcon4Btn = self:GetChild("Btn_PassiveGroup");--4技能
    self.mainReward = self:GetChild("mainReward")
    logicMgr.FuncOpenManager.refreshMainReward(self.mainReward,1120)

    ---@type FairyGUI.GGraph
    self.modelPos = self:GetChild("BossModel");

    self:addEvent();
    
    AudioManager.RefreshBGM()
    AudioManager.Play(111)
    
end

function UIGuildBoss:OnEnable()
    self:LocalListenEvent();
    unionHandler.reqUnionBossInfo(logicMgr.GuildManager.getUnionId(), logicMgr.GuildManager.getAllianceId());
end

function UIGuildBoss:OnDisable()
    self:LocalCloseEvent()
    self.bossBodyUrl = nil;
    --取消计时器
    if self.idleTimer then
        self.idleTimer:Stop();
    end
    self.idleTimer = nil;

    if self.refreshTimer then
        utimer.remove(self.refreshTimer);
        self.refreshTimer = nil;
    end
end

function UIGuildBoss:OnDestroy()
    -- WWISE.WwiseBehavior.Play(_bgmInfo.f_Event, "",nil,_audioType)
    AudioManager.RefreshBGM()
end

function UIGuildBoss:addEvent()
    --btnChangeFormation.onClick:Add(function()
    --    self.ShowSelectFom(1);
    --end);
    self:RegisterOnClick(self.backBtn, self.onCloseClick);
    self:RegisterOnClick(self.battleBtn, self.onOpenBattle);
    self:RegisterOnClick(self.rankBtn, self.onBossRank);
    self:RegisterOnClick(self.rankBackBtn, self.onCloseRank);
    self:RegisterOnClick(self.rankBackBGBtn, self.onCloseRank);
    self:RegisterOnClick(self.tipsBtn, self.onTip);
end

function UIGuildBoss:removeEvent()

end

function UIGuildBoss:LocalListenEvent()
    self:RegisterEvent(Config.EventType.Union_Hero_Rank_Info_S2C, self.initRankList, self);
    self:RegisterEvent(Config.EventType.FreashRoleInfoOther, self.GotOtherShowInfo, self);
    self:RegisterEvent(Config.EventType.Union_Boss_Info_S2C, self.initBoss, self);

    --self:RegisterEvent(Config.EventType.Union_Boss_Battle_S2C,self.)


end

function UIGuildBoss:LocalCloseEvent()
    self:UnRegisterEvent(Config.EventType.Union_Hero_Rank_Info_S2C, self.initRankList, self);
    self:UnRegisterEvent(Config.EventType.FreashRoleInfoOther, self.GotOtherShowInfo, self);
    self:UnRegisterEvent(Config.EventType.Union_Boss_Info_S2C, self.initBoss, self);
end
-------------------------Function------------
--初始化排行榜页面
function UIGuildBoss:initRankList()
    self.contributionListCtrl.selectedIndex = 1;
    if #self.guildBossInfo.rankInfo.playerList == 0 then
        self.noBodyRankCtrl.selectedIndex = 0;
    else
        self.noBodyRankCtrl.selectedIndex = 1;
        self.rankList.itemRenderer = self.rendererRank;
        self.rankList.numItems = #self.guildBossInfo.rankInfo.playerList;
    end
    self:rendererRankItem(self.guildBossInfo.rankInfo.myRank, self.guildBossInfo.rankInfo.selfInfo, self.myRank);

end
--初始化页面
function UIGuildBoss:initBoss()
    self.guildBossInfo = logicMgr.GuildManager.getGuideBossInfo();
    local bossCfg = self.guildBossInfo.bossInfo;
    local url = logicMgr.HeroManager.GetHeroDrawingPath(bossCfg.f_HeroID)
    if self.bossBodyUrl ~= url then
        self.bossBodyUrl = url;
        resMgr:LoadModelPrefab(url, function(go)
            local drawWrapper = self.drawWrapper;
            if (drawWrapper == nil) then
                drawWrapper = GoWrapper.New();
            end
            if (self.bossBody ~= nil) then
                destroyImmediate(self.bossBody);
            end
            self.bossBody = newObject(go);
            self.bossBody.name = url;--"self.bossBody";
            self.bossBody:AddComponent(TCanvas);

            drawWrapper:SetWrapTarget(self.bossBody, false)
            self.modelPos:SetNativeObject(drawWrapper);
            local showData = {}
            local scale, location = HeroManager.GetHeroLocationResize(bossCfg.f_HeroID)
            showData.location = location
            showData.scale = scale
            Util.Lua_SetLocalPositionXYZ(self.bossBody.transform, showData.location[1], showData.location[2], 0)
            Util.Lua_SetLocalScaleXYZ(self.bossBody.transform, showData.scale[1], showData.scale[2], 1)
            self.spineAnim  = self.bossBody:GetComponent("SkeletonGraphic")
            self:PlayShowIdle()
        end);
        --展示技能
        local skillId = nil;
        local obj = nil;
        local count = 1;
        while true do
            skillId = bossCfg["f_HeroSkill" .. count];
            if skillId == nil then
                break ;
            end
            obj = self["skillIcon" .. count .. "Btn"];
            if obj == nil then
                break
            end
            self:rendererBossSkill(obj, skillId);
            count = count + 1;
        end
    else

    end

    --显示奖励
    self.rewardList.itemRenderer = self.rendererReward;
    self.rewardList.numItems = #self.guildBossInfo.rewardsInfo;
    --刷新文本
    self.battleCount = G.dataTable["t_guildpara"]["7"].f_int_value - self.guildBossInfo.battleCount
    if self.battleCount <= 0 then
        self.battleCount = 0;
        self.battleBtn.enabled = false;
        self.redDotCtrl.selectedIndex = 0;
    else
        self.battleBtn.enabled = true;
        self.redDotCtrl.selectedIndex = 2;

    end
    --今日剩下次数
    self.timesTodayText.text = string.format(getLanguage("GuildInvestment_1125"), self.battleCount, G.dataTable["t_guildpara"]["7"].f_int_value)
    self.bossNameText.text = getLanguage("FunctionName1120");
    --倒计时
    self.curTime = self.guildBossInfo.bossRefreshTime - HelperFunc.GetServerTime();
    self.refreshTimer = utimer.timeCall(function()
        UIGuildBoss:refreshTime()
    end, 1000, -1)
    self:refreshTime()

end

--boss技能展示
function UIGuildBoss:rendererBossSkill(obj, skillId)
    local skillData = G.dataTable["t_skillinfo"][tostring(skillId)];
    obj.onClick:Clear();
    obj.onClick:Add(function()
        self.skillShowCtrl.selectedIndex = 1;
        self.skillName.text = getLanguage(skillData.f_SkillName);
        self.skillDec.text = getLanguage(skillData.f_Desc);
    end);
    obj:GetChild("Mask"):GetChild("Icon").url = "ui://SkillAtlas/" .. skillData.f_SkillIcon;
end

--奖励展示
function UIGuildBoss.rendererReward(idx, obj)
    local index = idx + 1;
    local id = UIGuildBoss.guildBossInfo.rewardsInfo[index];
    local data = logicMgr.ItemManager.getItemConstDatabyModelId(id);
    local itemCtr = CtrlManager.GetCtrl(PanelNames.Item);
    itemCtr.initData(obj:GetChild("n0"), data);
end
--排行榜展示
function UIGuildBoss.rendererRank(idx, obj)
    local index = idx + 1;

    local self = UIGuildBoss;
    local data = self.guildBossInfo.rankInfo.playerList[index];
    --data.point = self.guildBossInfo.rankInfo.playerList[index].online;
    self:rendererRankItem(index, data, obj);
end

function UIGuildBoss:rendererRankItem(index, data, obj)

    local item = obj;
    local Rank = item:GetChild("rank");
    local Name = item:GetChild("name");
    local Level = item:GetChild("level");
    local headIcon = item:GetChild("head"):GetChild("head"):GetChild("HeadIcon");
    local frame = item:GetChild("head"):GetChild("frame")
    local pointText = item:GetChild("point");
    local rankCtrl = item:GetController("rank");
    local noRankCtrl = item:GetController("ctrlNoRank");
    if index <= 0 then
        noRankCtrl.selectedIndex = 1;
    else
        noRankCtrl.selectedIndex = 0;
        if index > 3 then
            rankCtrl.selectedIndex = 3;
        else
            rankCtrl.selectedIndex = index - 1;
        end
    end

    headIcon.onClick:Clear();
    headIcon.onClick:Add(function()
        if tostring(data.playerId) ~= logicMgr.HeroManager.GetRoleId() then
            roleInfoHandler.sendreqOtherRoleInfo(data.playerId);
        end
    end)
    --headIcon.url = "ui://ICONAtlas/" .. logicMgr.HeroManager.GetHeroConfigbyModelId(tonumber(data.playerShowInfo.pic)).f_HeroIcon;
    headIcon.url = logicMgr.SkinManager.GetHeroIconBySkinId(data.playerShowInfo.pic);
    Rank.text = index;
    Name.text = data.playerShowInfo.name;
    Level.text = data.playerShowInfo.level;
    pointText.text = data.parameter;
    frame.url = "ui://ICONAtlas/" .. data.playerShowInfo.picFrame;
end

function UIGuildBoss:delayIdle()
    -- 调用loop的idea
    if UIGuildBoss.bossBody then
        UIGuildBoss.bossBody:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0, "idle1", true);
    end
end

function UIGuildBoss:GotOtherShowInfo(info)
    showUI(PanelNames.UIPlayerShow, info,nil,false,function()
        UIBottom.enterAdventure()
        showUI(PanelNames.UIGuild);
    end)
end

function UIGuildBoss:refreshTime()
    local self = UIGuildBoss;
    self.curTime = self.curTime - 1;
    local reset_time_str
    if self.curTime > 0 then
        reset_time_str = string.format(getLanguage("GuildInvestment_1122"),timeToTimeLeft(self.curTime, true))

    else
        if self.curTime == 0 then
            unionHandler.reqUnionBossInfo(logicMgr.GuildManager.getUnionId(), logicMgr.GuildManager.getAllianceId());
        end
        reset_time_str = string.format(getLanguage("GuildInvestment_1122"),timeToTimeLeft(0, true))

    end
    if self.reset_time_content == nil or self.reset_time_content ~= reset_time_str then
        self.resetTime.text = reset_time_str
        self.reset_time_content = reset_time_str
    end
end

function UIGuildBoss:PlayShowIdle()
    if self.spineAnim ~= nil then


        self.spineAnim.AnimationState:SetAnimation(0, "idle2", false);
        local idleAniTime = self.spineAnim.AnimationState.Data.SkeletonData:FindAnimation("idle2").Duration;
        if self.idleTimer == nil then
            self.idleTimer = Timer.New(UIGuildBoss.delayIdle, idleAniTime, 1, false);
        else
            self.idleTimer:Reset(UIGuildBoss.delayIdle, idleAniTime, 1, false);
        end
        self.idleTimer:Start();
    end
end

-------------------------------按钮监听
---关闭页面
function UIGuildBoss:onCloseClick()
    closeUI(PanelNames.UIGuildBoss);
    AudioManager.RefreshBGM()
end

function UIGuildBoss:onOpenBattle()
    GuildManager.Track_bossBattle()
    showUI(PanelNames.UIGuildBossBattleTeam);
end

function UIGuildBoss:onBossRank()
    unionHandler.reqUseHeroRank(logicMgr.GuildManager.getUnionId())
end

function UIGuildBoss:onCloseRank()
    self.contributionListCtrl.selectedIndex = 0;
end

function UIGuildBoss:onTip()
    logicMgr.UIShowManager.ShowCommonTips("GuildInvestment_1126", "GuildInvestment_1127")
end
return UIGuildBoss;